import 'dart:io';

import 'package:dio/dio.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';

import 'api.dart';

class HttpManager {
  Dio? _dio;
  static HttpManager? _instance;

  late PersistCookieJar _persistCookieJar;

  factory HttpManager.getInstance() {
    if (null == _instance) {
      _instance = new HttpManager._internal();
    }
    return _instance!;
  }

  // 构造方法的重载，命名构造函数
  HttpManager._internal() {
    // 初始化dio网络框架的超时时间
    BaseOptions options = new BaseOptions(
      baseUrl: Api.baseUrl, //基础地址
      connectTimeout: Duration(seconds: 5000), //链接服务器超时时间
      receiveTimeout: Duration(seconds: 3000), //读取超时时间
    );
    _dio = new Dio(options);
    _initDio();
  }

  void _initDio() async {
    // 初始化 dio网络框架的cookie拦截保存
    Directory directory = await getApplicationDocumentsDirectory();
    var path = Directory(join(directory.path, "cookie")).path;
    _persistCookieJar = PersistCookieJar(storage: FileStorage(path));
    _dio?.interceptors.add(CookieManager(_persistCookieJar));
  }
  
  request(url, {data, String method = "get"}) async {
    try {
      Options option = new Options(method: method);
      // dio框架自动配置好请求头等
      Response? response = await _dio?.request(url, data: data, options: option);
      print("request header : ${response?.requestOptions.headers}");
      print("response data : ${response?.data}");
      return response?.data;
    }catch (e) {
      print(e);
      return null;
    }
  }

  void clearCookie() {
    _persistCookieJar.deleteAll();
  }
}